<template>
  <el-dialog :title="title" :model-value="visible" @update:model-value="(value) => visible = value" width="800px" append-to-body @close="handleClose">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="水库名称" prop="reservoirName">
            <el-input v-model="formData.reservoirName" placeholder="请输入水库名称" :disabled="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="水库编码" prop="reservoirCode">
            <el-input v-model="formData.reservoirCode" placeholder="请输入水库编码" :disabled="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所在地区" prop="region">
            <el-input v-model="formData.region" placeholder="请输入所在地区" :disabled="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="水库类型" prop="reservoirType">
            <el-select v-model="formData.reservoirType" placeholder="请选择水库类型" style="width: 100%" :disabled="isView">
              <el-option label="大型" value="large" />
              <el-option label="中型" value="medium" />
              <el-option label="小型" value="small" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="库容量(万m³)" prop="capacity">
            <el-input-number v-model="formData.capacity" :min="0" :precision="2" placeholder="请输入库容量" style="width: 100%" :disabled="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="管理单位" prop="managementUnit">
            <el-input v-model="formData.managementUnit" placeholder="请输入管理单位" :disabled="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="formData.contactPerson" placeholder="请输入联系人" :disabled="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" :disabled="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status" :disabled="isView">
              <el-radio label="1">正常</el-radio>
              <el-radio label="2">维护</el-radio>
              <el-radio label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" :disabled="isView" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ isView ? '关 闭' : '取 消' }}</el-button>
        <el-button v-if="!isView" type="primary" @click="handleSubmit" :loading="loading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'

// 模拟API接口
const addReservoir = async (data: any) => {
  return { code: 200, msg: '新增成功' }
}

const updateReservoir = async (data: any) => {
  return { code: 200, msg: '修改成功' }
}

// Props
interface Props {
  modelValue: boolean
  title: string
  reservoirData?: any
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: '新增水库',
  reservoirData: null
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const formData = reactive({
  id: undefined,
  reservoirName: '',
  reservoirCode: '',
  region: '',
  reservoirType: undefined,
  capacity: undefined,
  managementUnit: '',
  contactPerson: '',
  contactPhone: '',
  status: '1',
  remark: ''
})

// 表单验证规则
const rules = reactive<FormRules>({
  reservoirName: [
    { required: true, message: '请输入水库名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  reservoirCode: [
    { required: true, message: '请输入水库编码', trigger: 'blur' },
    { pattern: /^[A-Z]{2}\d{3}$/, message: '编码格式不正确，如：SK001', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请输入所在地区', trigger: 'blur' }
  ],
  reservoirType: [
    { required: true, message: '请选择水库类型', trigger: 'change' }
  ],
  capacity: [
    { required: true, message: '请输入库容量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库容量必须大于等于0', trigger: 'blur' }
  ],
  managementUnit: [
    { required: true, message: '请输入管理单位', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => !!props.reservoirData?.id)
const isView = computed(() => props.title.includes('查看'))

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    reservoirName: '',
    reservoirCode: '',
    region: '',
    reservoirType: undefined,
    capacity: undefined,
    managementUnit: '',
    contactPerson: '',
    contactPhone: '',
    status: '1',
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 初始化表单数据
const initFormData = () => {
  if (props.reservoirData) {
    Object.assign(formData, {
      id: props.reservoirData.id,
      reservoirName: props.reservoirData.reservoirName || '',
      reservoirCode: props.reservoirData.reservoirCode || '',
      region: props.reservoirData.region || '',
      reservoirType: props.reservoirData.reservoirType || undefined,
      capacity: props.reservoirData.capacity || undefined,
      managementUnit: props.reservoirData.managementUnit || '',
      contactPerson: props.reservoirData.contactPerson || '',
      contactPhone: props.reservoirData.contactPhone || '',
      status: props.reservoirData.status || '1',
      remark: props.reservoirData.remark || ''
    })
  } else {
    resetForm()
  }
}

// 监听弹窗显示状态
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      initFormData()
    }
  },
  { immediate: true }
)

// 监听数据变化
watch(
  () => props.reservoirData,
  () => {
    if (props.modelValue) {
      initFormData()
    }
  },
  { deep: true }
)

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const submitData = { ...formData }
    
    if (isEdit.value) {
      await updateReservoir(submitData)
      ElMessage.success('修改成功')
    } else {
      delete submitData.id
      await addReservoir(submitData)
      ElMessage.success('新增成功')
    }
    
    emit('success')
    handleClose()
  } catch (error) {
    if (error !== false) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>